package com.net.xpay.common.manager.impl;

import com.net.common.dao.BasicMapper;
import com.net.common.dao.Page;
import com.net.common.exception.BusinessException;
import com.net.xpay.common.dao.SelfServiceAccountMapper;
import com.net.xpay.common.domain.SelfServiceAccount;
import com.net.xpay.common.manager.SelfServiceAccountManager;
import com.net.common.manager.AbstractManager;
import com.net.xpay.common.model.search.SelfServiceAccountSearchModel;
import com.net.xpay.core.constant.PoseidonErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Component
public class SelfServiceAccountManagerImpl extends AbstractManager<SelfServiceAccount> implements SelfServiceAccountManager {

    @Autowired
    private SelfServiceAccountMapper mapper;


    @Override
    protected BasicMapper<Long, SelfServiceAccount> getMapper() {
        return mapper;
    }

    @Override
    public List<SelfServiceAccount> search(SelfServiceAccountSearchModel searchModel) {
        Page page = new Page(searchModel);
        page.addOrder("id", "desc");
        return nonEmptyList(mapper.search(searchModel, page));
    }

    @Override
    public long searchCount(SelfServiceAccountSearchModel searchModel) {
        return mapper.searchCount(searchModel);
    }

    @Override
    public SelfServiceAccount doAdd(SelfServiceAccount model) {
        if (model.getOutBizNo() == null) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "订单号不能为空");
        }
        model.setOutBizNo(model.getOutBizNo().trim());
        SelfServiceAccount conditon = new SelfServiceAccount();
        conditon.setUserId(model.getUserId());
        conditon.setOutBizNo(model.getOutBizNo());
        Long count = mapper.selectCount(conditon);
        if (count > 0) {
            throw new BusinessException(PoseidonErrorCode.PARAMETER_ILLEGAL, "该订单号已存在");
        }
        model.setCreateTime(LocalDateTime.now());
        mapper.insert(model);
        return model;
    }

    @Override
    public SelfServiceAccount doUpdate(SelfServiceAccount model) {
        model.setModifyTime(LocalDateTime.now());
        mapper.updateByPrimaryKey(model);
        return model;
    }

    @Override
    public SelfServiceAccount doDetail(SelfServiceAccount model) {
        return mapper.selectByPrimaryKey(model.getId());
    }
}
